<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="标题" v-model="listQuery.title">
      </el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%">
      <el-table-column align="center" label="序号" width="65">
        <template slot-scope="scope">
          <span>{{scope.row.Id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200px" align="center" label="创建日期">
        <template slot-scope="scope">
          <span>{{scope.row.Create.substring(0,10)}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100px" label="脚本内容">
        <template slot-scope="scope">
          <span>{{scope.row.ScriptContent}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="类型">
        <template slot-scope="scope">
          <span>{{scope.row.ScriptFrom}}</span>
        </template>
      </el-table-column>
      <el-table-column  width="200px" align="center" label="脚本名称">
        <template slot-scope="scope">
          <span>{{scope.row.ScriptName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="delData(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="脚本名称" prop="ScriptName">
          <el-input v-model="temp.ScriptName"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="scriptFrom">
          <el-select class="filter-item" v-model="temp.scriptFrom" placeholder="请选择">
            <el-option v-for="item in  calendarTypeOptions" :key="item.key" label="手动录入" :value="item.display_name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="脚本内容" prop="scriptContent">
          <el-input v-model="temp.ScriptContent"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
        <el-button v-else type="primary" @click="updateData">更新</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="deldialogFormVisible">
      <template slot-scope="scope">
        <p style="text-align: center;font-size:24px;">确认要删除吗？</p>
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button @click="deldialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDelete()">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { getList, createScript, updateScript, deleteScript } from '@/api/script'
  import waves from '@/directive/waves' // 水波纹指令
  import { parseTime } from '@/utils'

  const calendarTypeOptions = [
    { key: 'HM', display_name: '手工录入' }
  ]

  // arr to obj ,such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'complexTable',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        delFormData: '',
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10
        },
        calendarTypeOptions,
        temp: {
          scriptName: '',
          scriptFrom: 'HM',
          scriptContent: '',
          create: new Date(),
          endtIime: new Date()
        },
        dialogFormVisible: false,
        deldialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改',
          create: '创建'
        },
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        getList(this.listQuery).then(response => {
          console.log(response.data.list)
          this.list = response.data.list
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      resetTemp() {
        this.temp = {
          importance: 1,
          remark: '',
          create: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      handleUpdate(row) {
        this.temp = Object.assign({}, row)
        console.log(this.temp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      },

      createData() {
        console.log(this.temp)
        if (this.temp.ScriptName == null || this.temp.ScriptContent == null) {
          this.$notify({
            title: '提交错误',
            message: '请填写完成字段',
            type: 'warning'
          })
        } else {
          createScript(this.temp).then(response => {
            if (response.data === 'OK') {
              this.dialogFormVisible = false
              this.total = this.total + 1
              this.getList()
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '添加失败',
                type: 'warning',
                duration: 2000
              })
            }
          }).catch(err => {
            console.log(1, err)
            this.$notify({
              title: '失败',
              message: '添加失败',
              type: 'warning',
              duration: 2000
            })
          })
        }
      },
      updateData(row) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.endTime = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            console.log(tempData)
            updateScript(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      delData(row) {
        this.deldialogFormVisible = true
        this.delFormData = row
      },
      handleDelete() {
        deleteScript(this.delFormData.Id).then(response => {
          if (response.data === 'OK') {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(this.delFormData)
            this.total = this.total - 1
            this.list.splice(index, 1)
            this.deldialogFormVisible = false
          } else {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'warning',
              duration: 2000
            })
          }
        }).catch(err => {
          this.fetchSuccess = false
          console.log(err)
          this.$notify({
            title: '失败',
            message: '删除失败',
            type: 'warning',
            duration: 2000
          })
        })
        this.deldialogFormVisible = false
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel(tHeader, data, 'table-list')
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
